# -*- coding: utf-8 -*-
"""
Created on Fri Sep  2 15:52:06 2022

@author: Ewing
"""
import configparser
import logging
import logging.handlers
import sys
import pandas as pd
import os
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QMessageBox, QApplication, QLabel

def run():
    if len(sys.argv) > 1:
        config_file_path = sys.argv[1]
    else:
        config_file_path = "config.ini"
    # config_file_path="C:\\Users\\pengzhongqi\\Desktop\\脚本\\MiniTools\\zengwei\\3\\config.ini"
    config = configparser.ConfigParser()
    config.read(config_file_path, encoding='utf-8')
    renamexls = config.get("renamejob", "renamexls")
    filepath = config.get("renamejob", "filepath")
    print("正在读取配置文件....")
    print("扫描路径:" + filepath)
    # print("模板路径:" + save_path)
    print("正在执行脚本-3-批量重命名")

    # 读取excel,设置列名为空并添加列名

    excel = pd.read_excel(renamexls, header=None, names=['A', 'B'])
    # 读取图片的路径
    file = os.listdir(filepath)

    # 将excel第二列的名字替换为图片名
    # item为图片路径下所有图片名
    for item in file:  # 遍历元素
        for i in range(len(excel)):  # 如果图片名和A列+jpg 或者 +jpeg相同
            if item == str(excel.iloc[i, 0]) + ".jpg" or item == str(
                    excel.iloc[i, 0]) + ".jpeg":  # 更改文件名字，由原来的文件名改为B列的值
                os.rename(filepath + "\\" + str(item), filepath + "\\new\\" + str(excel.iloc[i, 1]) + ".jpg")

    print("renamepic.py : The job has been done successfully")
    return True

class win(QWidget):
    def __init__(self):
        super().__init__()
        self.setFixedWidth(180)
        self.setWindowTitle(" ")

        layout = QVBoxLayout()
        openConfig = QPushButton("打开配置", self)
        # openConfig.setText()
        # openTemplate = QPushButton("打开配置模板", self)
        # openTemplate.setText()
        startButton = QPushButton("运行", self)

        layout.addWidget(QLabel("批量重命名"))
        # layout.addWidget(QLabel("文件"))
        layout.addWidget(openConfig)
        # layout.addWidget(openTemplate)
        # layout.addStretch()
        layout.addWidget(startButton)

        self.setLayout(layout)
        openConfig.clicked.connect(self.openConfig)
        # openTemplate.clicked.connect(self.openTemplate)
        startButton.clicked.connect(self.start)

    def openConfig(self):
        if len(sys.argv) > 1:
            config_file_path = sys.argv[1]
        else:
            config_file_path = "config.ini"
        print(config_file_path)
        # print(len(sys.argv))
        os.system(config_file_path)
        pass

    def start(self):
        try:
            res = run()
        except Exception as e:
            print(repr(e))
            res = False

        if res:
            QMessageBox.information(self, "", "处理成功！")
        else:
            QMessageBox.critical(self, "", "处理失败，请查看后台日志！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = win()
    main.show()
    sys.exit(app.exec())